import akshare as ak
import pandas as pd


# 获取交易所期货品种
def market_symbols():
    market_symbols_df = ak.market_futures_symbols(market="shfe")
    print(market_symbols_df)

# 获取期货合约的基本情况
def futures_zh_spot():
    futures_zh_spot_df = ak.futures_zh_spot()
    print(futures_zh_spot_df)

# 获取内盘-分时行情数据
def futures_zh_minute_sina():
    futures_zh_minute_sina_df = ak.futures_zh_minute_sina(symbol="rb2401", period="1")
    print(futures_zh_minute_sina_df)

# 获取分时行情数据并写入到CSV
def futures_zh_minute_sina_to_csv(symbol):
    futures_sina_df = ak.futures_zh_minute_sina(symbol=symbol, period="1")
    # 改列名
    futures_sina_df.columns = ['datetime', 'open_price', 'high_price', 'low_price', 'close_price', 'volume', 'hold']
    # 增加symbol列
    futures_sina_df['local_symbol'] = symbol+'.SHFE'
    # 增加symbol列
    futures_sina_df['open_interest'] = 0
    #futures_sina_df.index=pd.to_datetime(futures_sina_df.datetime, format='%Y-%m-%d %H:%M:%S')
    # 保存到CSV
    futures_sina_df.to_csv(symbol + ".csv",index=False)
# 获取分时行情数据并写入到CSV
def futures_zh_minute_sina_to_csv_bt(symbol):
    futures_sina_df = ak.futures_zh_minute_sina(symbol=symbol, period="1")
    # 改列名 Date,Open,High,Low,Close,Volume,OpenInterest
    futures_sina_df.columns = ['date', 'open', 'high', 'low', 'close', 'volume', 'hold']
    # 增加symbol列
    futures_sina_df['local_symbol'] = symbol+'.SHFE'
    # 增加symbol列
    futures_sina_df['openinterest'] = 0
    #futures_sina_df.index=pd.to_datetime(futures_sina_df.datetime, format='%Y-%m-%d %H:%M:%S')
    # 保存到CSV
    futures_sina_df.to_csv(symbol + ".csv",index=False)

# 获取分时行情数据最后一条并写入到CSV
def futures_zh_minute_sina_to_csv_last():
    ak.futures_zh_minute_sina(symbol="FU2401", period="1").tail(1).to_csv("FU2401_last.csv")

futures_zh_minute_sina_to_csv_bt('rb2401')
# futures_zh_minute_sina()